<template>
  <div>
    <el-form ref="form" :model="form" label-width="120px" :rules="rules">
      <el-form-item label="短信标题：" prop="messageTitle">
        <el-input v-model="form.messageTitle" />
      </el-form-item>
      <el-form-item label="选择模板：" prop="selectTemplate">
        <el-select
          v-if="messageTemplateList"
          v-model="form.selectTemplate"
          placeholder="模板"
          @change="changeTemplate"
        >
          <el-option
            v-for="item in messageTemplateList"
            :key="item.id"
            :label="item.templateTitle"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="短信模板内容：">
        <el-input
          v-model="form.messageContent"
          disabled
          type="textarea"
          :rows="3"
          show-word-limit
          maxlength="1000"
          resize="none"
        />
      </el-form-item>
      <el-form-item label="会员分组：" prop="groupingArr">
        <el-checkbox-group v-model="form.groupingArr" @change="changeGroup">
          <el-checkbox
            v-for="item in MEMBER_LEVEL.children"
            :key="item.id"
            :label="item.dicName"
            :value="item.dicCode"
          />
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="会员标签：">
        <el-checkbox-group v-model="form.labelsArr" @change="changeLabelsArr">
          <el-checkbox
            v-for="item in labelsArr"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="发送时间：">
        <el-date-picker
          v-model="form.sendSmsTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime"
          placeholder="选择发送时间"
        />
      </el-form-item>
    </el-form>
    <el-table :data="tableData">
      <el-table-column prop="information" label="信息项" />
      <el-table-column prop="content" label="内容">
        <template slot-scope="scope">
          <el-input v-model="scope.row.content" placeholder="请输入内容" />
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align:center;margin-top:20px;">
      <el-button type="primary" @click="cache">暂存</el-button>
      <el-button type="primary" @click="submitForm">发送短信</el-button>
    </div>
    <el-dialog center width="700px" title="短信模版内容" :visible.sync="innerVisible" append-to-body>
      <p>{{ innerDialogContent }}</p>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sendShortMessage">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      innerVisible: false,
      rules: {
        messageTitle: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        selectTemplate: [
          { required: true, message: "模版不能为空", trigger: "change" }
        ],
        groupingArr: [
          {
            type: "array",
            required: true,
            message: "会员分组不能为空",
            trigger: "change"
          }
        ]
      },
      labelsArr: [],
      form: {
        appId: "",
        grouping: [],
        groupingArr: [],
        id: "",
        messageContent: "",
        messageTitle: "",
        messageType: 1,
        msgId: "",
        phone: "",
        sendSmsTime: "",
        sendStatus: false,
        selectTemplate: "",
        labels: [],
        labelsArr: []
      },
      tableData: [],
      checkBox: [],
      MEMBER_LEVEL: {},
      appIdList: [],
      messageTemplateList: [],
      selectObject: {},
      innerDialogContent: ""
    };
  },
  mounted() {
    this.getInitDate();
    this.$post({
      url: "/manage/label/getLabel",
      data: {
        keyword: "",
        page: {
          maxResultCount: 0,
          pageNo: 0,
          pageSize: 10,
          skipCount: 0
        },
        type: 1
      }
    }).then(res => {
      this.labelsArr = res.items.items;
    });
  },
  methods: {
    cache() {
      this.sendShortMessage(true);
    },
    changeGroup(res) {
      const result = [];
      res.forEach(v => {
        this.MEMBER_LEVEL.children.forEach(vv => {
          if (vv.dicName === v) {
            result.push(vv.dicCode);
          }
        });
      });
      this.form.grouping = result;
    },
    changeLabelsArr(res) {
      const result = [];
      res.forEach(v => {
        this.labelsArr.forEach(vv => {
          if (vv.label === v) {
            result.push(vv.id);
          }
        });
      });
      this.form.labels = result;
    },
    sendShortMessage(res) {
      let result = this.messageTemplateList.filter(
        v => v.id === this.form.selectTemplate
      )[0].appId
      this.setMsgContent()
      this.$post({
        url: "/manage/messages/createMessage",
        data: {
          item: {
            appid: Number(result),
            grouping: this.form.grouping,
            messageContent: this.innerDialogContent,
            messageTitle: this.form.messageTitle,
            messageType: 1,
            sendStatus: 2,
            sendTime: this.form.sendSmsTime,
            labels: this.form.labelsArr
          }
        }
      }).then(res => {
        if (res) {
          this.innerVisible = false;
          this.$emit("closeDialog");
          return false;
        }
        this.$post({
          url: "/manage/messages/sendMessages",
          data: {
            id: res
          }
        }).then(res => {
          this.innerVisible = false;
          this.$emit("closeDialog");
          this.$message({
            message: "操作成功",
            type: "success"
          });
        });
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.setMsgContent();
          this.innerVisible = true;
        }
      });
    },
    setMsgContent() {
      let str = this.form.messageContent;
      let a = "";
      let arr = JSON.parse(JSON.stringify(this.tableData));
      let replaceStr = (arr, str) => {
        a = str.replace(`{${arr[0].information}}`, arr[0].content);
        arr.shift();
        arr.length ? replaceStr(arr, a) : "";
      };
      replaceStr(arr, str);
      this.innerDialogContent = a;
    },
    changeTemplate() {
      this.selectObject = this.messageTemplateList.filter(
        v => v.id === this.form.selectTemplate
      )[0];
      this.form.messageContent = this.selectObject.templateContent;
      const str = this.selectObject.templateContent;
      const a = str.split("}");
      const b = [];
      a.forEach(v => {
        const d = v.indexOf("{") !== -1 ? v.substr(v.indexOf("{") + 1) : "";
        d.length ? b.push(d) : "";
      });
      this.tableData = b.map(v => {
        return {
          information: v,
          content: ""
        };
      });
    },
    getInitDate() {
      this.$post({
        url: "/manage/messages/loadCreateMessagePage",
        data: {}
      }).then(res => {
        this.MEMBER_LEVEL = res.MEMBER_LEVEL;
        this.appIdList = res.appIdList;
        this.messageTemplateList = res.messageTemplateList;
        res.MEMBER_LEVEL.children.forEach((v, index) => {
          this.checkBox.push({ code: v.dicCode, bool: false });
        });
      });
    }
  }
};
</script>

<style>
</style>
